import React, {useEffect} from 'react';
import {Alert, App, Button, Card, Descriptions, Space, Table} from "antd";
import {Link, useLocation, useNavigate} from "react-router-dom";
import {SecurityPath} from "type/SecurityPath";
import LogFactory from "log/LogFactory";
import {SecurityRole} from "type/SecurityRole";
import {requestDelete, requestGet} from "util/request";
import {ColumnsType} from "antd/es/table";
import {AlertProps, Divider} from "antd/lib";
import ButtonGroup from "antd/es/button/button-group";
import {useAppDispatch} from "../../../redux/hook";
import {fetchDeleteData} from "../../../redux/reducer/pathReducer";

const log = LogFactory.getLog("PathDeleteComponent");

const roleColumns: ColumnsType<SecurityRole> = [
    {
        dataIndex: 'index',
        title: '序号' ,
        width: 60,
        align: "center" ,
        key: 'index',
        render: (value, record, index) => {
            return <strong> {index + 1} </strong> ;
        }
    },
    {
        key: 'id',
        dataIndex: 'id',
        title: '角色编号',
    },
    {
        key: 'authority',
        dataIndex: 'authority',
        title: '角色定义',
    },
    {
        key: 'explain',
        dataIndex: 'explain',
        title: '角色描述',
    }
];

const PathDeleteComponent = () => {
    const path: SecurityPath = useLocation().state ;
    const { message } = App.useApp() ;
    const navigate = useNavigate() ;
    const dispatch = useAppDispatch() ;
    const [data,setData] = React.useState<SecurityRole[]>([]) ;
    const [alterData, setAlterData] = React.useState<AlertProps>({
        message: "路径没有与角色绑定关系 !",
        type: "success",
        showIcon: true,
    }) ;

    useEffect(() => {
        requestGet<SecurityRole[]>("/security-role-path/roles/" + path.id).then(res => {
            log.debug("与路径相关的角色列表：",res) ;
            if (res.data.length > 0){
                setData(res.data) ;
                setAlterData({
                    message: `路径 [${path.pattern}] 与以下角色存在绑定关系,如果要删除路径，请先解除以下角色与路径的关联 !`,
                    type: "error",
                    showIcon: true,
                });
            }
        }) ;
    },[]) ;

    /**
     * 解除路径与角色绑定关系
     */
    const unbind = async () => {
        let res = await requestDelete<number>("/security-role-path/" + path.id, {}).then(res => res) ;
        if(res.data > 0){
            message.success("解除路径与角色绑定关系成功！") ;
            setData([])
            setAlterData({
                message: "路径角色绑定关系已解除,允许删除路径 !",
                type: "success",
                showIcon: true,

            })
        }else {
            message.warning("解除路径与角色绑定关系失败！") ;
        }
    }

    /**
     * 删除路径
     */
    const deletePath = async () => {
        let res = await dispatch(fetchDeleteData(path.id)).unwrap().then(res => res) ;
        if (res > 0) {
            message.success("删除路径成功！");
            navigate("", {replace: true});
        }else{
            message.warning("删除路径失败！");
        }
    }

    return (
        <Card
            title={"删除路径"}
            extra={ <Link key={"path-list"} to={""}>路径列表</Link>}
        >
            <Descriptions
                bordered={true} column={2} size={"small"}>
                <Descriptions.Item label="路径编号">{path.id}</Descriptions.Item>
                <Descriptions.Item label="路径KEY">{path.key}</Descriptions.Item>
                <Descriptions.Item label="路径模式">{path.pattern}</Descriptions.Item>
                <Descriptions.Item label="路径描述">{path.explain}</Descriptions.Item>
            </Descriptions>
            <Divider/>
            <Space>
                <ButtonGroup>
                    <Button type={"primary"} disabled={data.length === 0 } onClick={unbind} >解除绑定关系</Button>
                    <Button type={"primary"} danger disabled={data.length !== 0} onClick={deletePath}>删除路径信息</Button>
                </ButtonGroup>
            </Space>
            <Table<SecurityRole>
                title={() => <Alert {...alterData} />}
                dataSource={data}
                columns={roleColumns}
            />
        </Card>
    );
};
export default PathDeleteComponent;